package com.lm.controller;

import com.lm.model.CountData;
import com.lm.model.LmTrackEvent;
import com.lm.service.LmUpdateService;
import com.meirengu.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("update")
public class UpdateController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UpdateController.class);

    @Autowired
    LmUpdateService lmUpdateService;

    private final SimpleDateFormat simpleFormatter = new SimpleDateFormat("yyyy-MM-dd");

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET)
    public void update() {

        Map<String, Object> params = new HashMap<>();

        List<LmTrackEvent> trackEventList = lmUpdateService.getAll();

        int total = trackEventList.size();
        int i = 1;

        for (LmTrackEvent item : trackEventList) {
            params.put("productId", item.getProductId());
            params.put("dataDate", formatter(item.getDataDate()));

            CountData countData = lmUpdateService.getCount1(params);

            params.put("id", item.getId());
            params.put("countIp", countData.getCountIp());
            params.put("countSessionId", countData.getCountSessionId());

            lmUpdateService.updateTrackEvent(params);

            logger.info("update track evnet : " + (i * 100 / total));
        }

    }

    private String formatter(Date date) {
        return simpleFormatter.format(date);
    }

}
